package com.x86.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.github.pagehelper.PageInfo;
import com.x86.domain.*;
import com.x86.service.*;
import com.x86.util.FileUploadUtil;
import com.x86.util.GetIpUtil;
import com.x86.util.JwtUtil;
import com.x86.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author 风亦未止
 * @date 2022/3/26 15:01
 */
@Api(tags = "管理员后台操作")
@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    public PreDataService preDataService;
    @Autowired
    public RecordService recordService;
    @Autowired
    public UserService userService;
    @Autowired
    public ComputerService computerService;
    @Autowired
    public BatchService batchService;
    @Autowired
    public HttpServletRequest httpServletRequest;
    @Autowired
    public UserLoginLogService userLoginLogService;
    @Autowired
    public FeedbackService feedbackService;
    @Autowired
    public CTestService cTestService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public ResponseResult login(@RequestBody UserVO user) throws IOException {
        if (StringUtils.isEmpty(user.getNickname())||StringUtils.isEmpty(user.getPassword())) return ResponseResult.failure("请输入完整信息");
        String ip = GetIpUtil.getIp(httpServletRequest);
        //ip信息
        String ipInfo = GetIpUtil.getCityInfo(ip);
        return userService.login(user,ip,ipInfo);
    }

    @ApiOperation(value = "获取所有批次机器的数据")
    @GetMapping("/allData")
    public ResponseResult getData(@RequestHeader("Token") String token,
                                  @RequestParam(value = "page",defaultValue = "1") @ApiParam(value = "页码") int pageNum,
                                  @RequestParam(value = "limit",defaultValue = "20") @ApiParam(value = "每页条数") int pageSize){
        PageInfo<ComputerVO> list = computerService.getList(pageSize, pageNum);
        List<ComputerVO> dataList = list.getList();
        int size = computerService.count();
        int currPageNum = list.getPageNum();
        HashMap<String, Object> data = new HashMap<>();
        data.put("total",size);
        data.put("currPage",currPageNum);
        data.put("list",dataList);
        return ResponseResult.success("成功！",data);
    }

    @ApiOperation(value = "分批获取机器信息")
    @GetMapping("/data/{id}")
    public ResponseResult getRecord(@RequestHeader("Token") String token,
                                    @PathVariable("id") @ApiParam(value = "批次id") Integer batchId,
                                    @RequestParam(value = "page",defaultValue = "1") @ApiParam(value = "页码") int pageNum,
                                    @RequestParam(value = "limit",defaultValue = "20") @ApiParam(value = "每页条数") int pageSize){
        Batch batchByid = batchService.getById(batchId);
        if (ObjectUtil.isNull(batchByid))return ResponseResult.failure("该批次不存在！");
        Batch batch = new Batch();
        batch.setBatchid(batchId);
        PageInfo<ComputerVO> list = computerService.getComInfoByBatch(pageSize, pageNum, batch);
        List<ComputerVO> dataList = list.getList();
        int size = list.getSize();
        int currPageNum = list.getPageNum();
        HashMap<String, Object> data = new HashMap<>();
        data.put("total",size);
        data.put("currPage",currPageNum);
        data.put("batchnum",batchByid.getName());
        data.put("list",dataList);
        return ResponseResult.success("成功！",data);
    }

    @ApiOperation(value = "获取批次信息")
    @GetMapping("/batchInfo")
    public ResponseResult getBatchInfo(@RequestHeader("Token") String token){
        List<Batch> info = batchService.getInfo();
        int size=info.size();
        HashMap<String,Object> data=new HashMap<>();
        data.put("total",size);
        data.put("list",info);
        return ResponseResult.success("成功！",data);
    }

    @ApiOperation(value = "获取登录日志列表")
    @GetMapping("/log")
    public ResponseResult getLog(@RequestHeader("Token") String token,
                                 @RequestParam(value = "page",defaultValue = "1") @ApiParam(value = "页码") int pageNum,
                                  @RequestParam(value = "limit",defaultValue = "20") @ApiParam(value = "每页条数") int pageSize){
        PageInfo<UserLoginLogVO> pageInfo = userLoginLogService.getLogList(pageSize, pageNum);
        List<UserLoginLogVO> list = pageInfo.getList();
        int size = userLoginLogService.getLogCount();
        HashMap<String,Object> data=new HashMap<>();
        data.put("total",size);
        data.put("currPage",pageInfo.getPageNum());
        data.put("list",list);
        return ResponseResult.success("成功！",data);
    }

    @ApiOperation(value = "添加反馈")
    @PostMapping("/feedback")
    public ResponseResult addfeedback(@RequestHeader("Token") String token,
                                      @RequestBody FeedbackVO feedbackVO){
        Integer userId = JwtUtil.getUserId(token);
        Feedback feedback = new Feedback();
        feedback.setEmail(feedbackVO.getEmail());
        feedback.setPhone(feedbackVO.getPhone());
        feedback.setText(feedbackVO.getText());
        feedback.setUserid(userId);
        boolean save = feedbackService.save(feedback);
        if (save){
            return ResponseResult.success("成功！");
        }
        return ResponseResult.failure("失败！");
    }

    @ApiOperation(value = "查看我的反馈")
    @GetMapping("/myFeedback")
    public ResponseResult myFeedback(@RequestHeader("Token") String token,
                                     @RequestParam(value = "page",defaultValue = "1") @ApiParam(value = "页码") int pageNum,
                                     @RequestParam(value = "limit",defaultValue = "20") @ApiParam(value = "每页条数") int pageSize){
        Integer userId = JwtUtil.getUserId(token);
        PageInfo<FeedbackVO2> myFeedback = feedbackService.getMyFeedback(userId, pageSize, pageNum);
        HashMap<String,Object> data=new HashMap<>();
        data.put("currPage",myFeedback.getPageNum());
        data.put("list",myFeedback.getList());
        return ResponseResult.success("成功！",data);
    }

    @ApiOperation(value = "查看所有反馈")
    @GetMapping("/feedbackList")
    public ResponseResult feedbackList(@RequestHeader("Token") String token,
                                     @RequestParam(value = "page",defaultValue = "1") @ApiParam(value = "页码") int pageNum,
                                     @RequestParam(value = "limit",defaultValue = "20") @ApiParam(value = "每页条数") int pageSize){
        PageInfo<FeedbackVO2> pageInfo = feedbackService.getFeedbackList(pageSize, pageNum);
        int count = feedbackService.count();
        HashMap<String,Object> data=new HashMap<>();
        data.put("total",count);
        data.put("currPage",pageInfo.getPageNum());
        data.put("list",pageInfo.getList());
        return ResponseResult.success("成功！",data);
    }

    @ApiOperation(value = "删除个人反馈")
    @DeleteMapping ("/delete/{id}")
    public ResponseResult delete(@RequestHeader("Token") String token,
                                 @PathVariable("id")@ApiParam(value = "反馈的") Integer id){
        Integer userId = JwtUtil.getUserId(token);
        Feedback feedback = feedbackService.getById(id);
        if (ObjectUtil.isNull(feedback)) return ResponseResult.failure("该条反馈不存在！");
        if (feedback.getUserid().equals(userId)){
            boolean b = feedbackService.removeById(feedback);
            if (b){
                return ResponseResult.success("删除成功!");
            }
            return ResponseResult.failure("失败！");
        }
        return ResponseResult.failure("该条反馈不属于你！不能删除！");
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/changePassword")
    public ResponseResult changePassword(@RequestHeader("Token") String token,
                                         @RequestParam("originalPassword")@ApiParam(value = "原密码") String originalPassword,
                                         @RequestParam("newPassword")@ApiParam(value = "新密码") String newPassword){
        Integer userId = JwtUtil.getUserId(token);
        User user = userService.getById(userId);
        if (!user.getPassword().equals(originalPassword))return ResponseResult.failure("原密码错误！");
        user.setPassword(newPassword);
        boolean b = userService.updateById(user);
        if (b){
            return ResponseResult.failure("密码修改成功！");
        }
        return ResponseResult.failure("密码修改失败！");
    }

    @ApiOperation(value = "7天内设备设备数量")
    @GetMapping("/7day")
    public ResponseResult changePassword(@RequestHeader("Token") String token){
        Integer comListBy7day = computerService.getComListBy7day();
        List<DayDetail> dayDetail = computerService.getDayDetail();
        HashMap<String, Object> data = new HashMap<>();
        data.put("total",comListBy7day);
        data.put("detail",dayDetail);
        return ResponseResult.success("成功！",data);
    }

    @ApiOperation(value = "配置文件上传")
    @PostMapping("/file")
    public ResponseResult save(@RequestHeader("Token") String token,
                               @RequestParam("file") @ApiParam(value = "文件") MultipartFile file,
                               HttpServletRequest request){
        String s = FileUploadUtil.uploadUtil(file, request);
        if (s==null)return ResponseResult.failure("上传失败！");
        return ResponseResult.success("上传成功！",s);
    }

    @ApiOperation(value = "根据机器id获取后测数据")
    @GetMapping("/getTest/{cid}")
    public ResponseResult getTestData(@RequestHeader("Token") String token,
                                      @PathVariable("cid")@ApiParam("机器id") String cid){
        Computer byId = computerService.getById(cid);
        if(ObjectUtil.isNull(byId))return ResponseResult.failure("该机器不存在！");
        TestVO testDataById = cTestService.getTestDataById(cid);
        return ResponseResult.success("成功！",testDataById);
    }




}
